class Friction1 extends egret.Sprite {
    private ball : Ball
    private bouncing : number = -1
    private friction : number = 0.1

    public constructor() {
        super()
        this.once( egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage():void {
        this.stage.scaleMode = egret.StageScaleMode.NO_SCALE
        this.ball = new Ball()
        this.ball.x = this.stage.stageWidth / 2
        this.ball.y = this.stage.stageHeight / 2
        this.ball.vx = Math.random() * 10 - 5
        this.ball.vy = Math.random() * 10 - 5
        this.addChild(this.ball)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event:egret.Event):void {
        let speed : number = Math.sqrt(this.ball.vx * this.ball.vx + this.ball.vy * this.ball.vy)
        let angle : number = Math.atan2(this.ball.vy, this.ball.vx)
        if (speed > this.friction) {
            speed -= this.friction
        } else {
            speed = 0
        }
        this.ball.vx = Math.cos(angle) * speed
        this.ball.vy = Math.sin(angle) * speed

        this.ball.x += this.ball.vx
        this.ball.y += this.ball.vy
        let left = 0
        let right = this.stage.stageWidth
        let top = 0
        let bottom = this.stage.stageHeight

        if (this.ball.x + this.ball.radius > right) {
            this.ball.x = right - this.ball.radius
            this.ball.vx *= this.bouncing
        } else if (this.ball.x - this.ball.radius < left) {
            this.ball.x = left + this.ball.radius
            this.ball.vx *= this.bouncing
        }

        if (this.ball.y + this.ball.radius > bottom) {
            this.ball.y = bottom - this.ball.radius
            this.ball.vy *= this.bouncing
        } else if (this.ball.y - this.ball.radius < top) {
            this.ball.y = top + this.ball.radius
            this.ball.vy *= this.bouncing
        }
    }
}